package com.meizi.drop.redisdemo.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author meizi
 * @email enjoymeizi@gmail.com
 * @date 2021/1/21 10:09
 */
@RestController
public class TestRedissonController {
    @Autowired
    RedissonClient client;
    @GetMapping("hello")
    public String hello(){
        RLock lock = client.getLock("my-lock");
        //1.锁会有默认30秒的过期时间
        //2.会自动续期 默认30秒的看门狗 10秒一续期
//        lock.lock(10, TimeUnit.SECONDS);  主动设置锁的过期时间，锁到期后不会自动续期
        lock.lock();
        try{
            System.out.println("获得锁:"+Thread.currentThread().getId());
            Thread.sleep(3000);
        }catch (Exception e){

        }finally {
            System.out.println("释放锁:"+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";

    }
}
